﻿using CommonAdmin.Dto;
using CommonAdmin.Model;
using CommonAdmin.Util;
using CommonAdmin.Web.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text.Json.Nodes;
using System.Text.Json;
namespace CommonAdmin.Web.Controllers.Api
{
	[ApiController]
	[Route("api/[controller]")]
	public class RoleController : ApiBaseController
	{
		public RoleController(ILogger<RoleController> logger, ISqlSugarClient db) : base(logger, db) { }
		/// <summary>
		/// 角色列表(分页)
		/// </summary>
		/// <param name="page"></param>
		/// <param name="limit"></param>
		/// <param name="keyword"></param>		
		/// <returns></returns>
		[HttpGet("list")]
		public JsonResult GetList(int page,int limit,string keyword)
		{			
			ResultViewModel result = new ResultViewModel();
			try
			{
				result.code = (int)CodeEnum.请求成功;
				int total = 0;
				var list=_db.Queryable<RoleDto>()
					.WhereIF(!string.IsNullOrWhiteSpace(keyword),o=>o.Name.Contains(keyword)||o.Bak.Contains(keyword))					
					.OrderBy(o=>o.CreateTime)
					.ToPageList(page, limit, ref total);
				result.rows = total;
				result.data = list;
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "获取角色列表失败");
			}
			return new JsonResult(result);
		}
		/// <summary>
		/// 角色列表(不分页)
		/// </summary>
		/// <param name="page"></param>
		/// <param name="limit"></param>
		/// <param name="keyword"></param>		
		/// <returns></returns>
		[HttpGet("listall")]
		public JsonResult GetList()
		{
			ResultViewModel result = new ResultViewModel();
			try
			{
				result.code = (int)CodeEnum.请求成功;
				int total = 0;
				var list = _db.Queryable<RoleDto>()
					.OrderBy(o => o.CreateTime)
					.ToList();
				result.rows = total;
				result.data = list;
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "获取角色列表失败");
			}
			return new JsonResult(result);
		}
		/// <summary>
		/// 添加角色
		/// </summary>
		/// <param name="data"></param>
		/// <returns></returns>
		[HttpPost("add")]
		public JsonResult Add([FromBody] JsonObject data)
		{
			string name = data["name"]!.GetValue<string>();
			string bak = data["bak"]!.GetValue<string>();			
			ResultViewModel result = new ResultViewModel();
			if (string.IsNullOrWhiteSpace(name))
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "角色名称不能为空";
				return new JsonResult(result);
			}
			if (_db.Queryable<RoleDto>().Where(o => o.Name == name).Count() > 0)
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "角色名称已存在";
				return new JsonResult(result);
			}
			var dto = new RoleDto()
			{
				Id = Tools.NewGuid(),
				Name = name,
				Bak = bak,				
				CreateTime = DateTime.Now,
				UpdateTime = DateTime.Now,
			};
			try
			{
				result.code = (int)CodeEnum.请求成功;
				_db.Insertable<RoleDto>(dto).ExecuteCommand();				
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "添加角色失败");				
			}
			if (result.code == (int)CodeEnum.请求成功)
			{//记录日志
				base.SaveDbLog<RoleDto>("添加角色",null,dto);
			}
			return new JsonResult(result);
		}
		/// <summary>
		/// 删除角色
		/// </summary>
		/// <param name="data"></param>
		/// <returns></returns>
		[HttpPost("del")]
		public JsonResult Delete([FromBody] JsonObject data)
		{
			string id = data["id"]!.GetValue<string>();
			ResultViewModel result = new ResultViewModel();
			if (string.IsNullOrWhiteSpace(id))
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "角色Id不能为空";
				return new JsonResult(result);
			}
			if (id == Constants.SystemId)
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "内置角色不能删除";
				return new JsonResult(result);
			}
			var role = _db.Queryable<RoleDto>().First(o=>o.Id==id);
			try
			{
				result.code = (int)CodeEnum.请求成功;				
				_db.Deleteable<RoleDto>(role).ExecuteCommand();				
			}
			catch(Exception ex)
			{				
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "删除角色失败");
			}
			if (result.code == (int)CodeEnum.请求成功)
			{//记录日志
				base.SaveDbLog<RoleDto>("删除角色",role,null);
			}
			return new JsonResult(result);
		}
		/// <summary>
		/// 修改角色
		/// </summary>
		/// <param name="data"></param>
		/// <returns></returns>
		[HttpPost("edit")]		
		public JsonResult Update([FromBody] JsonObject data)
		{
			string id = data["id"]!.GetValue<string>();
			string name = data["name"]!.GetValue<string>();
			string bak = data["bak"]!.GetValue<string>();			
			ResultViewModel result = new ResultViewModel();
			if (string.IsNullOrWhiteSpace(id))
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "角色Id不能为空";
				return new JsonResult(result);
			}
			if (id == Constants.SystemId)
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "内置角色不能修改";
				return new JsonResult(result);
			}
			var oldRole = _db.Queryable<RoleDto>().First(o => o.Id == id);
			var newRole = new RoleDto()
			{
				Id = id,
				Name = name,
				Bak = bak,				
				UpdateTime = DateTime.Now,
			};
			try
			{
				result.code = (int)CodeEnum.请求成功;
				_db.Updateable<RoleDto>(newRole)
				.IgnoreColumns(o => new { o.CreateTime })
				.ExecuteCommand();
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "修改角色失败");
			}
			if (result.code == (int)CodeEnum.请求成功)
			{//记录日志
				base.SaveDbLog<RoleDto>("修改角色",oldRole,newRole);
			}
			return new JsonResult(result);
		}
		/// <summary>
		/// 角色权限
		/// </summary>
		/// <param name="data"></param>
		/// <returns></returns>
		[HttpPost("permission")]
		public JsonResult Permission([FromBody] JsonObject data)
		{
			string id = data["id"]!.GetValue<string>();
			string permission = data["permission"]!.GetValue<string>();			
			ResultViewModel result = new ResultViewModel();
			if (string.IsNullOrWhiteSpace(id))
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "角色Id不能为空";
				return new JsonResult(result);
			}
			if (id == Constants.SystemId)
			{
				result.code = (int)CodeEnum.请求失败;
				result.msg = "内置角色权限不能修改";
				return new JsonResult(result);
			}
			try
			{
				result.code = (int)CodeEnum.请求成功;
				//_db.Updateable<RoleDto>(new RoleDto()
				//{
				//	Id = int.Parse(id),
				//	Name = name,
				//	Bak = bak,
				//	Status = (EnumStatus)Enum.Parse(typeof(EnumStatus), status)
				//}).ExecuteCommand();
			}
			catch (Exception ex)
			{
				result.code = (int)CodeEnum.内部错误;
				result.msg = CodeEnum.内部错误.ToString();
				_logger.LogError(ex, "修改角色权限失败");
			}
			return new JsonResult(result);
		}
	}
}
